package com.d3works.apps.account.web;

import com.d3works.apps.account.db.DepositSlip;
import com.d3works.apps.account.db.PaymentVoucher;
import com.d3works.apps.account.db.repo.DepositSlipRepository;
import com.d3works.apps.account.service.DepositSlipService;
import com.d3works.db.mapper.Adapter;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.time.LocalDate;
import java.util.List;

@Singleton
public class DepositSlipController {

  public void loadPaymentVoucherDueList(ActionRequest request, ActionResponse response) {

    DepositSlip depositSlip = request.getContext().asType(DepositSlip.class);
    DepositSlipService depositSlipService = Beans.get(DepositSlipService.class);
    response.setValue(
        "__paymentVoucherDueList", depositSlipService.fetchPaymentVouchers(depositSlip));
  }

  public void updateDepositChequeDate(ActionRequest request, ActionResponse response) {

    LocalDate chequeDate =
        (LocalDate)
            Adapter.adapt(
                request.getContext().get("__depositDate"), LocalDate.class, LocalDate.class, null);
    DepositSlip depositSlip = request.getContext().asType(DepositSlip.class);
    List<PaymentVoucher> paymentVouchers = depositSlip.getPaymentVoucherList();
    paymentVouchers.stream().forEach(paymentVoucher -> paymentVoucher.setChequeDate(chequeDate));
    response.setValue("paymentVoucherList", paymentVouchers);
  }

  public void publish(ActionRequest request, ActionResponse response) {
    DepositSlip depositSlip = request.getContext().asType(DepositSlip.class);
    depositSlip = Beans.get(DepositSlipRepository.class).find(depositSlip.getId());
    DepositSlipService depositSlipService = Beans.get(DepositSlipService.class);

    try {
      depositSlipService.publish(depositSlip);
      response.setNotify(I18n.get("The deposit slip is published"));
      response.setReload(true);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void validate(ActionRequest request, ActionResponse response) {
    DepositSlip depositSlip = request.getContext().asType(DepositSlip.class);
    depositSlip = Beans.get(DepositSlipRepository.class).find(depositSlip.getId());
    DepositSlipService depositSlipService = Beans.get(DepositSlipService.class);

    try {
      depositSlipService.validate(depositSlip);
      response.setNotify(I18n.get("The deposit slip is validated"));
      response.setReload(true);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }
}
